{% extends "base.html" %}

{% block title %}查看排班 - 算法生成照护计划{% endblock %}

{% block page_title %}查看排班{% endblock %}

{% block extra_css %}
<style>
    .schedule-table {
        font-size: 0.9rem;
    }
    
    .schedule-table th, .schedule-table td {
        padding: 0.5rem;
    }
    
    .time-slot-row:nth-child(odd) {
        background-color: rgba(0, 0, 0, 0.05);
    }
    
    .time-slot-row:hover {
        background-color: rgba(0, 123, 255, 0.1);
    }
    
    .schedule-filter {
        margin-bottom: 20px;
        padding: 15px;
        border: 1px solid #dee2e6;
        border-radius: 5px;
        background-color: #f8f9fa;
    }
    
    .schedule-visualization {
        margin-top: 20px;
    }
    
    .timeline {
        display: flex;
        flex-direction: column;
        margin-top: 20px;
    }
    
    .timeline-row {
        display: flex;
        margin-bottom: 5px;
    }
    
    .timeline-label {
        width: 100px;
        padding-right: 10px;
        text-align: right;
        font-weight: bold;
    }
    
    .timeline-slots {
        display: flex;
        flex-grow: 1;
    }
    
    .timeline-slot {
        flex-grow: 1;
        height: 30px;
        margin: 0 1px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 0.7rem;
        color: white;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }
    
    .timeline-tooltip {
        position: relative;
    }
    
    .timeline-tooltip:hover::after {
        content: attr(data-tooltip);
        position: absolute;
        bottom: 100%;
        left: 50%;
        transform: translateX(-50%);
        background-color: rgba(0, 0, 0, 0.8);
        color: white;
        padding: 5px;
        border-radius: 3px;
        white-space: nowrap;
        z-index: 1000;
    }
    
    .activity-color-1 { background-color: #007bff; }
    .activity-color-2 { background-color: #28a745; }
    .activity-color-3 { background-color: #dc3545; }
    .activity-color-4 { background-color: #ffc107; color: #212529; }
    .activity-color-5 { background-color: #17a2b8; }
    .activity-color-6 { background-color: #6c757d; }
    .activity-color-7 { background-color: #6610f2; }
    .activity-color-8 { background-color: #fd7e14; }
    .activity-color-9 { background-color: #20c997; }
    .activity-color-10 { background-color: #e83e8c; }
    .activity-color-0 { background-color: #343a40; }
</style>
{% endblock %}

{% block content %}
<div class="row">
    <div class="col-md-12">
        <div class="card">
            <div class="card-header">
                <h5 class="card-title">查看排班</h5>
            </div>
            <div class="card-body">
                <div class="schedule-filter">
                    <form id="scheduleFilterForm">
                        <div class="row">
                            <div class="col-md-4">
                                <label for="elder" class="form-label">老人</label>
                                <select class="form-select" id="elder" name="elder">
                                    <option value="">-- 请选择老人 --</option>
                                    {% for elder in elders %}
                                    <option value="{{ elder.id }}">{{ elder.elder }}</option>
                                    {% endfor %}
                                </select>
                            </div>
                            <div class="col-md-4">
                                <label for="date" class="form-label">日期</label>
                                <input type="date" class="form-control" id="date" name="date" value="{{ date.today().isoformat() }}">
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">&nbsp;</label>
                                <div class="d-grid">
                                    <button type="submit" class="btn btn-primary">查询</button>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
                
                <div id="loading" style="display: none;" class="text-center my-4">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">加载中...</span>
                    </div>
                    <p>正在加载排班数据，请稍候...</p>
                </div>
                
                <div id="scheduleResult" style="display: none;">
                    <div class="alert alert-danger" id="errorMessage" style="display: none;"></div>
                    
                    <div id="scheduleData">
                        <h5>老人：<span id="elderName"></span></h5>
                        <h6>日期：<span id="scheduleDate"></span></h6>
                        
                        <div class="schedule-visualization">
                            <h6>照护计划可视化</h6>
                            <div id="timeline" class="timeline"></div>
                        </div>
                        
                        <div class="mt-4">
                            <h6>照护计划详情</h6>
                            <div class="table-responsive">
                                <table class="table table-bordered schedule-table">
                                    <thead>
                                        <tr>
                                            <th>时间段</th>
                                            <th>活动</th>
                                            <th>活动ID</th>
                                            <th>护理员</th>
                                            <th>护理员ID</th>
                                        </tr>
                                    </thead>
                                    <tbody id="scheduleTableBody">
                                    </tbody>
                                </table>
                            </div>
                        </div>
                        
                        <div class="mt-4">
                            <a id="downloadLink" href="#" class="btn btn-success">
                                <i class="fas fa-download"></i> 下载排班表
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
    $(document).ready(function() {
        // 获取URL参数
        const urlParams = new URLSearchParams(window.location.search);
        const elderParam = urlParams.get('elder');
        const dateParam = urlParams.get('date');
        
        // 如果URL中有参数，则自动填充表单并提交
        if (elderParam) {
            $('#elder').val(elderParam);
        }
        
        if (dateParam) {
            $('#date').val(dateParam);
        }
        
        if (elderParam && dateParam) {
            $('#scheduleFilterForm').submit();
        }
        
        // 表单提交
        $('#scheduleFilterForm').submit(function(e) {
            e.preventDefault();
            
            const elder = $('#elder').val();
            const date = $('#date').val();
            
            if (!elder) {
                alert('请选择老人');
                return;
            }
            
            if (!date) {
                alert('请选择日期');
                return;
            }
            
            // 显示加载中
            $('#loading').show();
            $('#scheduleResult').hide();
            $('#errorMessage').hide();
            
            // 发送请求
            $.ajax({
                url: `/view_schedule?elder=${elder}&date=${date}`,
                type: 'GET',
                success: function(response) {
                    $('#loading').hide();
                    $('#scheduleResult').show();
                    
                    if (response.error) {
                        $('#errorMessage').text(response.error).show();
                        return;
                    }
                    
                    // 更新下载链接
                    $('#downloadLink').attr('href', `/download_schedule/${elder}?date=${date}`);
                    
                    // 显示老人和日期
                    $('#elderName').text(elder);
                    $('#scheduleDate').text(date);
                    
                    // 清空表格
                    $('#scheduleTableBody').empty();
                    
                    // 填充表格
                    if (response.time_slots && response.time_slots.length > 0) {
                        response.time_slots.forEach(function(slot) {
                            $('#scheduleTableBody').append(`
                                <tr class="time-slot-row">
                                    <td>${slot.time_slot}</td>
                                    <td>${slot.activity}</td>
                                    <td>${slot.activity_id}</td>
                                    <td>${slot.caregiver}</td>
                                    <td>${slot.caregiver_id}</td>
                                </tr>
                            `);
                        });
                        
                        // 生成时间线可视化
                        generateTimeline(response.time_slots);
                    } else {
                        $('#scheduleTableBody').append(`
                            <tr>
                                <td colspan="5" class="text-center">没有找到排班数据</td>
                            </tr>
                        `);
                        
                        $('#timeline').html('<p class="text-center">没有找到排班数据</p>');
                    }
                },
                error: function(xhr, status, error) {
                    $('#loading').hide();
                    $('#scheduleResult').show();
                    
                    // 显示错误消息
                    let errorMsg = '加载排班数据失败！';
                    if (xhr.responseJSON && xhr.responseJSON.error) {
                        errorMsg += ' ' + xhr.responseJSON.error;
                    }
                    $('#errorMessage').text(errorMsg).show();
                }
            });
        });
        
        // 生成时间线可视化
        function generateTimeline(timeSlots) {
            const timeline = $('#timeline');
            timeline.empty();
            
            // 按照活动类型分组
            const activityGroups = {};
            const activityColors = {};
            let colorIndex = 1;
            
            timeSlots.forEach(function(slot) {
                const activity = slot.activity;
                
                if (!activityGroups[activity]) {
                    activityGroups[activity] = [];
                    activityColors[activity] = colorIndex % 11; // 11种颜色循环
                    colorIndex++;
                }
                
                activityGroups[activity].push(slot);
            });
            
            // 创建时间线
            const timeSlotCount = timeSlots.length;
            
            // 创建时间刻度
            const timeScaleRow = $('<div class="timeline-row"></div>');
            const timeScaleLabel = $('<div class="timeline-label">时间</div>');
            const timeScaleSlots = $('<div class="timeline-slots"></div>');
            
            timeSlots.forEach(function(slot, index) {
                const timeSlot = $(`<div class="timeline-slot" style="background-color: #f8f9fa; color: #212529;">${slot.time_slot}</div>`);
                timeScaleSlots.append(timeSlot);
            });
            
            timeScaleRow.append(timeScaleLabel);
            timeScaleRow.append(timeScaleSlots);
            timeline.append(timeScaleRow);
            
            // 创建活动时间线
            for (const activity in activityGroups) {
                const activityRow = $('<div class="timeline-row"></div>');
                const activityLabel = $(`<div class="timeline-label">${activity}</div>`);
                const activitySlots = $('<div class="timeline-slots"></div>');
                
                // 创建空白槽
                for (let i = 0; i < timeSlotCount; i++) {
                    activitySlots.append($('<div class="timeline-slot" style="background-color: transparent;"></div>'));
                }
                
                // 填充活动槽
                activityGroups[activity].forEach(function(slot) {
                    const index = timeSlots.findIndex(s => s.time_slot === slot.time_slot);
                    if (index !== -1) {
                        const activitySlot = $(activitySlots.children()[index]);
                        activitySlot.addClass(`activity-color-${activityColors[activity]}`);
                        activitySlot.addClass('timeline-tooltip');
                        activitySlot.attr('data-tooltip', `${slot.time_slot}: ${activity} (${slot.caregiver})`);
                        activitySlot.text(slot.caregiver);
                    }
                });
                
                activityRow.append(activityLabel);
                activityRow.append(activitySlots);
                timeline.append(activityRow);
            }
        }
    });
</script>
{% endblock %}
